package com.yechaoa.pictureselectordemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;
import com.yechaoa.pictureselectordemo.db.DataManager;
import com.yechaoa.pictureselectordemo.db.SuceptorOperationHistory;
import com.yechaoa.pictureselectordemo.db.SusceptorListModel;
import com.yechaoa.pictureselectordemo.util.APIUtils;
import com.yechaoa.pictureselectordemo.util.HttpParameter;
import com.yechaoa.pictureselectordemo.util.HttpResult;
import com.yechaoa.pictureselectordemo.util.ImageProcessHelper;
import com.yechaoa.pictureselectordemo.util.JSONUtils;
import com.yechaoa.pictureselectordemo.util.Loading;
import com.yechaoa.pictureselectordemo.util.MyException;
import com.yechaoa.pictureselectordemo.util.NetworkManager;
import com.yechaoa.pictureselectordemo.util.WebUrl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import static com.yechaoa.pictureselectordemo.MainActivity.EvThisPage.startup_hello;

public class MainActivity extends AppCompatActivity implements   NavigationView.OnNavigationItemSelectedListener{

    enum EvThisPage
    {
        reg_panhao,
        pop_err_msg,
        pop_info_msg,
        startup_hello,
        refresh_suscep_id_list,
        upload_success,
    };
    private int maxSelectNum = 9;
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private RecyclerView mRecyclerView;
    private PopupWindow pop;
    private Button button1;
    private AlertDialog alertDialog2; //单选框
    private AlertDialog alertDialog3;
    private AlertDialog alertDialog1;

    @BindView(R.id.navigation_view)
    NavigationView navigation_view;

    private ArrayAdapter<String> panhao_arr_adapter;

    @BindView(R.id.textViewOPType)
    TextView textViewOPType;

    @BindView(R.id.textViewChamberID)
    TextView textViewChamberID;

    String[] items_op_types =  {"烤炉进入前", "从烤炉取出", "反应腔待长盘", "反应腔长完的盘"};
    String[] items_cham_names= {"A8-A", "A8-B", "A7-A", "480-A", "480-B"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = findViewById(R.id.recycler);
        //绑定处理
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);

        initWidget();

        // 检查网络
        WebServerHello();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case(android.R.id.home):
                {
                drawerLayout.openDrawer(GravityCompat.START);
                return true;
            }
            case R.id.action_delete_history:
            {
                cleanHistory();
            }
            case R.id.action_download_settings: {
                Loading.noDialogRun(MainActivity.this, new Runnable() {

                    @Override
                    public void run() {
                        try {
                            HttpResult hr =
                                    APIUtils.postForObject(WebUrl.REQ_SUSCEP_NAME_LIST_URL,
                                            HttpParameter.create().add("cham",textViewChamberID.getText().toString()));
                            if (hr.hasError()) {
                                throw hr.getError();
                            }
                            List<SusceptorListModel> ids = (List<SusceptorListModel>) JSONUtils.fromJson(hr.jsonArray.toString(), new TypeToken<List<SusceptorListModel>>() {
                            }.getType());
                            Pair<EvThisPage, Object> p = new Pair<EvThisPage, Object>(EvThisPage.refresh_suscep_id_list, ids);
                            EventBus.getDefault().post(p);
                        } catch (Exception e) {
                            Pair<EvThisPage, String> p = new Pair<EvThisPage, String>(EvThisPage.pop_err_msg, e.toString());
                            EventBus.getDefault().post(p);
                        }
                    }

                });
                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void cleanHistory() {
        SharedPreferences sp =getSharedPreferences(getString(R.string.panhao_pref_name),0);
        SharedPreferences.Editor editor=sp.edit();
        editor.clear();
        editor.commit();
        Toast.makeText(this, "清除成功", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    private void initWidget() {

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
            //显示标题
            getSupportActionBar().setDisplayShowTitleEnabled(true);
            getSupportActionBar().setTitle("  石墨盘使用记录 ");


        }

        navigation_view.setNavigationItemSelectedListener(this);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(MainActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(MainActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(MainActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
//
        // 获取搜索记录文件内容
        SharedPreferences sp = getSharedPreferences("panhao_search_history", 0);
        String history = sp.getString("history", "暂时没有搜索记录");

        // 用逗号分割内容返回数组
        String[] history_arr = history.split(",");

        // 新建适配器，适配器数据为搜索历史文件内容
        panhao_arr_adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, history_arr);

        // 保留前50条数据
        if (history_arr.length > 50) {
            String[] newArrays = new String[50];
            // 实现数组之间的复制
            System.arraycopy(history_arr, 0, newArrays, 0, 50);
            panhao_arr_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_dropdown_item_1line, history_arr);
        }
        tv_panhao1.setAdapter(panhao_arr_adapter);
    }



    public void showSingleAlertDialog(View view){

        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);

        if(view.getId() == R.id.textViewChamberID) {
            alertBuilder.setTitle("选择chamber");
            alertBuilder.setSingleChoiceItems(items_cham_names, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
//                    Toast.makeText(MainActivity.this, items2[i], Toast.LENGTH_SHORT).show();
                    textViewChamberID.setText(items_cham_names[i]);
                }
            });
        }else if(view.getId() == R.id.textViewOPType) {
            alertBuilder.setTitle("选择当前状态");
            alertBuilder.setSingleChoiceItems(items_op_types, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
//                    Toast.makeText(MainActivity.this, items1[i], Toast.LENGTH_SHORT).show();
                    textViewOPType.setText(items_op_types[i]);
                }
            });
        }
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog2.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog2.dismiss();
            }
        });

        alertDialog2 = alertBuilder.create();
        alertDialog2.show();
    }



    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @SuppressLint("CheckResult")
        @Override
        public void onAddPicClick() {
            //获取写的权限
            RxPermissions rxPermission = new RxPermissions(MainActivity.this);
            rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission permission) {
                            if (permission.granted) {// 用户已经同意该权限
                                //第一种方式，弹出选择和拍照的dialog
                                showPop();

                                //第二种方式，直接进入相册，但是 是有拍照得按钮的
//                                showAlbum();
                            } else {
                                Toast.makeText(MainActivity.this, "拒绝", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    };

    private void showAlbum() {
        //参数很多，根据需要添加
        PictureSelector.create(MainActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(maxSelectNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选PictureConfig.MULTIPLE : PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(true)// 是否裁剪
                .compress(true)// 是否压缩
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                //.selectionMedia(selectList)// 是否传入已选图片
                //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                //.compressMaxKB()//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效
                //.compressWH() // 压缩宽高比 compressGrade()为Luban.CUSTOM_GEAR有效
                //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                .rotateEnabled(false) // 裁剪是否可旋转图片
                //.scaleEnabled()// 裁剪是否可放大缩小图片
                //.recordVideoSecond()//录制视频秒数 默认60s
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    private void showPop() {
        View bottomView = View.inflate(MainActivity.this, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
//        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv_album:
                        //相册
                        PictureSelector.create(MainActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_camera:
                        //拍照
                        PictureSelector.create(MainActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_cancel:
                        //取消
                        //closePopupWindow();
                        break;
                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }
    @BindView(R.id.tv_panhao1)
    AutoCompleteTextView tv_panhao1;
    private ArrayAdapter<String> arrayAdapter;
    @BindView(R.id.tv_panhao2)
    EditText tv_panhao2;
    @BindView(R.id.tv_panhao3)
    EditText tv_panhao3;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调

                images = PictureSelector.obtainMultipleResult(data);
                selectList.addAll(images);

                //selectList = PictureSelector.obtainMultipleResult(data);

                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                adapter.setList(selectList);
                adapter.notifyDataSetChanged();
            }else if(requestCode == swap_req_pan_code)
            {
                images = PictureSelector.obtainMultipleResult(data);
                if(images.size() < 0)
                {
                    Toast.makeText(MainActivity.this, "没有图片", Toast.LENGTH_SHORT).show();
                    return ;
                }
                Bitmap bitmap = BitmapFactory.decodeFile(images.get(0).getPath());
                float ratio = 800.0F/bitmap.getWidth();
                bitmap =  ImageProcessHelper.scaleBitmap(bitmap,ratio);
                images = PictureSelector.obtainMultipleResult(data);
                // post to server
                if (!NetworkManager.isNetworkAvailable(MainActivity.this))
                    Toast.makeText(this, R.string.network_invalid, Toast.LENGTH_SHORT).show();

                //上传服务器到后台
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] datas = baos.toByteArray();
                final String imageDatasString = Base64.encodeToString(datas, Base64.DEFAULT);
                Loading.run(this, new Runnable() {

                    @Override
                    public void run() {
                        try {
                            HttpResult hr =
                                    APIUtils.postForObject(WebUrl.RECG_SUSCEP_NAME_URL,
                                    HttpParameter.create().
                                            add("pic", imageDatasString));
                            if (hr.hasError()) {
                                throw hr.getError();
                            }
                            String words_num = JSONUtils.getString(hr.jsonObject, "words_num");
                            String words = JSONUtils.getString(hr.jsonObject, "words");
                            Pair<EvThisPage, String> p = new Pair<EvThisPage, String>(EvThisPage.pop_err_msg,"识别成功：" + words);
                            EventBus.getDefault().post(p);
                            p = new Pair<EvThisPage, String>(EvThisPage.reg_panhao,words);
                            EventBus.getDefault().post(p);
                        } catch (Exception e) {
                            Pair<EvThisPage, String> p = new Pair<EvThisPage, String>(EvThisPage.pop_err_msg,e.toString());
                            EventBus.getDefault().post(p);
                        }
                    }
                });
//                Date d = new Date();
//                tv_panhao1.setText(d.toString());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(Pair<MainActivity.EvThisPage,Object> p)    {

        if (p.first == EvThisPage.reg_panhao) {
            this.tv_panhao1.setText(p.second.toString());
        } else if (p.first == EvThisPage.pop_info_msg ) {
            Toast.makeText(MainActivity.this, p.second.toString(), Toast.LENGTH_SHORT).show();

        }
        else if ( p.first == EvThisPage.pop_err_msg) {
            Toast.makeText(MainActivity.this, p.second.toString(), Toast.LENGTH_LONG).show();

        }
        else if (p.first == EvThisPage.refresh_suscep_id_list) {
            List<SusceptorListModel> ids = (List<SusceptorListModel>) p.second;
            String[] ids_ = new String[ids.size()];
            for (int i = 0; i < ids.size(); i++)
                ids_[i] = ids.get(i).getSusceptorID();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.
                    this, android.R.layout.simple_dropdown_item_1line, ids_);
            tv_panhao1.setAdapter(adapter);
        } else if (p.first == EvThisPage.upload_success) {
            Toast.makeText(MainActivity.this, p.second.toString(), Toast.LENGTH_SHORT).show();
            tv_panhao1.setText("");
            tv_panhao2.setText("");

        }else if(p.first == EvThisPage.startup_hello)
        {
            JSONObject words = (JSONObject) p.second;
            try {
                String lastStartup = words.getString("服务器上次启动时间");
                String CHAM_NAMES = words.getString("CHAM_NAMES");
                String OP_TYPES = words.getString("OP_TYPES");
                items_cham_names = CHAM_NAMES.split(",");
                items_op_types = OP_TYPES.split(",");
                Toast.makeText(MainActivity.this, "服务器上次启动时间 "+lastStartup, Toast.LENGTH_SHORT).show();
            }catch (JSONException e)
            {
                Toast.makeText(MainActivity.this, "解析启动回复错误："+e.toString(), Toast.LENGTH_SHORT).show();
            }

        }

    }
    @OnClick(R.id.tv_sweep_panhao)
    public void onViewClicked() {
        PermissionReq.with(this)
                .permissions(Manifest.permission.CAMERA)
                .result(new PermissionReq.Result() {
                    @Override
                    public void onGranted() {
                        //拍照
                        PictureSelector.create(MainActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .forResult(swap_req_pan_code);
                    }

                    @Override
                    public void onDenied() {
                        SnackbarUtils.show(MainActivity.this, "没有相机权限，无法打开扫一扫！");
                    }
                })
                .request();
    }
    @BindView(R.id.activity_main)
    DrawerLayout drawerLayout;
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//
//        return super.onOptionsItemSelected(item);
//    }

    @OnClick({R.id.buttonUpload})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.buttonUpload:

                postWholeDataToServer();
                break;

        }
    }

    private void savePanhaoToPref(String text) {
        SharedPreferences mysp = getSharedPreferences(getString(R.string.panhao_pref_name), 0);
        String old_text = mysp.getString("history", "暂时没有搜索记录");

        // 利用StringBuilder.append新增内容，逗号便于读取内容时用逗号拆分开
        StringBuilder builder = new StringBuilder(old_text);
        builder.append(text + ",");

        // 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
        if (!old_text.contains(text + ",")) {
            SharedPreferences.Editor myeditor = mysp.edit();
            myeditor.putString("history", builder.toString());
            myeditor.commit();
            Toast.makeText(this, text + "添加成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, text + "已存在", Toast.LENGTH_SHORT).show();
        }
    }

    private void postWholeDataToServer() {
        if( tv_panhao1.getText().length() <= 0 || tv_panhao2.getText().length() <= 0)
        {
            Toast.makeText(MainActivity.this, "信息输入不完整", Toast.LENGTH_SHORT).show();
            return;
        }

        savePanhaoToPref(tv_panhao1.getText().toString());
        Loading.noDialogRun(MainActivity.this, new Runnable() {

            @Override
            public void run() {
                String picsBase64 = "";
                for (int i = 0; i < selectList.size(); i++) {
                    LocalMedia m = selectList.get(i);
//            if(m.isCompressed())
                    {
                        picsBase64 += imageToBase64(m.getPath()) + ",";
                    }
                }


                try {
                    HttpResult hr =
                            APIUtils.postForObject(WebUrl.REQ_UPLOAD_SUSCEPTOR_FORM_URL,
                                    HttpParameter.create().
                                            add("panhao", tv_panhao1.getText().toString())
                                            .add("recipe", tv_panhao2.getText().toString())
                                            .add("remark", tv_panhao3.getText().toString())
                                            .add("chamber", textViewChamberID.getText().toString())
                                            .add("operation", textViewOPType.getText().toString())
                                            .add("pics", picsBase64)
                            );
                    if (hr.hasError()) {
                        throw hr.getError();
                    }
                    savetoDB();
                    Pair<EvThisPage, String> p = new Pair<EvThisPage, String>(EvThisPage.upload_success, "上传成功 ");
                    EventBus.getDefault().post(p);
                } catch (Exception e) {
                    Pair<EvThisPage, String> p = new Pair<EvThisPage, String>(EvThisPage.pop_err_msg, e.toString());
                    EventBus.getDefault().post(p);
                }
            }});
    }

    /**
     * 将图片转换成Base64编码的字符串
     */
    public static String imageToBase64(String path){
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.DEFAULT);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        drawerLayout.closeDrawers();
        new Handler().postDelayed(() -> item.setChecked(false), 500);
        Intent intent = new Intent();
        switch (item.getItemId()) {
            case R.id.action_history:
                intent.setClass(this, HistoryActivity.class);
                startActivity(intent);
                return true;
//            case R.id.action_qrcode:
//                intent.setClass(this, QRCodeActivity.class);
//                startActivity(intent);
//                return true;
//            case R.id.action_share:
//                share();
//                return true;
//            case R.id.action_about:
//                intent.setClass(this, AboutActivity.class);
//                startActivity(intent);
//                return true;
        }
        return false;
    }
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private void savetoDB() throws FileNotFoundException {
        SuceptorOperationHistory his = new SuceptorOperationHistory();
        his.setPanhao_id_1(tv_panhao1.getText().toString());
        his.setPanhao_id_2(tv_panhao2.getText().toString());
        his.setPanhao_id_3(tv_panhao3.getText().toString());
        his.setChamber(textViewChamberID.getText().toString());
        his.setOp_param(textViewOPType.getText().toString());
        his.setOp_datetime(formatter.format(new Date()));
        String picsBase64 = "";
//        for(int i=0;i<selectList.size();i++)
//        {
//            LocalMedia m = selectList.get(i);
////            if(m.isCompressed())
//            {
//                picsBase64+= imageToBase64(m.getPath())+",";
//            }
//        }
        his.setPicture_of_op(picsBase64);
        DataManager.getInstance().updateHistory(his);
    }

    private void WebServerHello()
    {
        Loading.run(this, new Runnable() {

            @Override
            public void run() {
                try {
                    HttpResult hr =
                            APIUtils.postForObject(WebUrl.hello_URL,
                                    HttpParameter.create());
                    if (hr.hasError()) {
                        throw hr.getError();
                    }
                    JSONObject words = hr.jsonObject;
                    Pair<EvThisPage, JSONObject> p = new Pair<EvThisPage, JSONObject>(EvThisPage.startup_hello,words);
                    EventBus.getDefault().post(p);

                } catch (Exception e) {
                    Pair<EvThisPage, String> p = new Pair<EvThisPage, String>(EvThisPage.pop_err_msg,e.toString());
                    EventBus.getDefault().post(p);
                }
            }
        });
    }
    final static int swap_req_pan_code = 1234;
    final static int swap_req_recipe_name = 1235;
}
